//
//  ToolView.m
//  79环信
//
//  Created by 刘恒槟 on 15/8/2.
//  Copyright (c) 2015年 刘恒槟. All rights reserved.
//

#import "ToolView.h"
#import <AVFoundation/AVFoundation.h>
#import "MyTextView.h"
#import "EMVoiceConverter.h"

typedef enum : NSUInteger {
    ButtonTypeFaceButton,
    ButtonTypeVoiceButton,
    ButtonTypeFuncButton,
    ButtonTypeKBButton,
} ButtonType;

@interface ToolView ()<MyTextViewDelegate>

@property (nonatomic, strong) MyTextView * textView;
@property (nonatomic, strong) UIButton * faceBtn;
@property (nonatomic, strong) UIButton * funcBtn;
@property (nonatomic, strong) UIButton * recoderBtn;
@property (nonatomic, strong) UIButton * speakBtn;

@property(nonatomic,strong)AVAudioRecorder * audioRecorder;
@property(nonatomic,strong)NSURL * voice_url;

@end

@implementation ToolView

-(instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        [self setupZujians];
        [self setupAutoLayout];
        
    }
    
    return self;
}

-(void)setupZujians{
    
    self.speakBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.speakBtn setImage:[UIImage imageNamed:@"chatBar_record"] forState:UIControlStateNormal];
    self.speakBtn.tag = ButtonTypeVoiceButton;
    [self.speakBtn addTarget:self action:@selector(tapVoiceButton) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.speakBtn];
    
    self.textView = [[MyTextView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    [self.textView.layer setCornerRadius:3];
    self.textView.delegate = self;
    self.textView.MyTextViewdelegate = self;
    self.textView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.textView];
    self.textView.hidden = NO;
    
    self.faceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.faceBtn setImage:[UIImage imageNamed:@"chatBar_face"] forState:UIControlStateNormal];
    self.faceBtn.tag = ButtonTypeFaceButton;
    [self.faceBtn addTarget:self action:@selector(tapFaceButton) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.faceBtn];
    
    self.funcBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.funcBtn setImage:[UIImage imageNamed:@"chatBar_more"] forState:UIControlStateNormal];
    self.funcBtn.tag = ButtonTypeFuncButton;
    [self.funcBtn addTarget:self action:@selector(tapFuncButton) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.funcBtn];
    
    self.recoderBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.recoderBtn setTitle:@"按住录音" forState:UIControlStateNormal];
    self.recoderBtn.backgroundColor = [UIColor whiteColor];
    [self.recoderBtn.layer setCornerRadius:3];
    [self.recoderBtn addTarget:self action:@selector(stratRecord) forControlEvents:UIControlEventTouchDown];
    [self.recoderBtn addTarget:self action:@selector(stopRecord) forControlEvents:UIControlEventTouchUpInside];
    [self.recoderBtn addTarget:self action:@selector(cancelRecord) forControlEvents:UIControlEventTouchUpOutside];
    [self addSubview:self.recoderBtn];
    
    self.recoderBtn.hidden = YES;
    
}

-(void)setupAutoLayout{
    
    NSDictionary * dic = NSDictionaryOfVariableBindings(_textView,_speakBtn,_faceBtn,_funcBtn,_recoderBtn);
    self.speakBtn.translatesAutoresizingMaskIntoConstraints = NO;
    self.faceBtn.translatesAutoresizingMaskIntoConstraints = NO;
    self.funcBtn.translatesAutoresizingMaskIntoConstraints = NO;
    self.textView.translatesAutoresizingMaskIntoConstraints = NO;
    self.recoderBtn.translatesAutoresizingMaskIntoConstraints = NO;
    
    
    NSArray * c1 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_speakBtn(44)][_textView][_faceBtn(44)][_funcBtn(44)]|" options:0 metrics:nil views:dic];
    NSArray * c2 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_speakBtn][_recoderBtn][_faceBtn][_funcBtn]|" options:0 metrics:nil views:dic];
    NSArray * c3 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_speakBtn(44)]" options:0 metrics:nil views:dic];
    NSArray * c4 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_faceBtn(44)]" options:0 metrics:nil views:dic];
    NSArray * c5 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_funcBtn(44)]" options:0 metrics:nil views:dic];
    
    NSArray * c6 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[_textView(30)]-5-|" options:0 metrics:nil views:dic];
    NSArray * c7 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[_recoderBtn(30)]-5-|" options:0 metrics:nil views:dic];
    
    
    [self addConstraints:c1];
    
    [self addConstraints:c2];
    [self addConstraints:c3];
    [self addConstraints:c4];
    [self addConstraints:c5];
    [self addConstraints:c6];
    [self addConstraints:c7];
    
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if ([text isEqualToString:@"\n"]) {
        NSString * str = [self.textView imageText];
        if (self.sendBlockHandle) {
            
            self.sendBlockHandle(str);
            
            self.textView.text = @"";
        }
    }
    return YES;
}


-(void)TextView:(MyTextView *)textView DidTapFunctionItem:(NSInteger)index{
    
    switch (index) {
            
        case 0:
            if (self.tapFunction) {
                self.tapFunction(FunctionPhoto);
            }
            break;
        case 1:
            
            if (self.tapFunction) {
                self.tapFunction(FunctionCamera);
            }
            break;
        case 2:
            if (self.tapFunction) {
                self.tapFunction(FunctionVideo);
            break;
        case 3:
            if (self.tapFunction) {
                self.tapFunction(FunctionLocation);
            }
            break;
        case 4:
            if (self.tapFunction) {
                self.tapFunction(FunctionVoiceCall);
            }
        }
            break;
        case 5:
        if (self.tapFunction) {
            self.tapFunction(FunctionVideoCall);
            }
            break;
            
        default:
            break;
    }
}
-(void)tapFaceButton
{
    
    if (self.faceBtn.tag == ButtonTypeFaceButton) {
        
        [self changeToolViewWithType:ButtonTypeFaceButton];
        
    }else if (self.faceBtn.tag == ButtonTypeKBButton){
        
        [self changeToolViewWithType:ButtonTypeKBButton];
    }
}
-(void)tapVoiceButton{
    
    if (self.speakBtn.tag == ButtonTypeVoiceButton)
    {
        
        [self changeToolViewWithType:ButtonTypeVoiceButton];
        
    }
    else if (self.speakBtn.tag == ButtonTypeKBButton)
    {
        
        [self changeToolViewWithType:ButtonTypeKBButton];
    }
}
-(void)tapFuncButton
{
    
    if (self.funcBtn.tag == ButtonTypeFuncButton)
    {
        
        [self changeToolViewWithType:ButtonTypeFuncButton];
        
    }
    else if (self.funcBtn.tag == ButtonTypeKBButton)
    {
        
        [self changeToolViewWithType:ButtonTypeKBButton];
    }
    
}
-(void)changeToolViewWithType:(ButtonType)type{
    
    switch (type) {
        case ButtonTypeFaceButton:
        {
            [self.faceBtn setImage:[UIImage imageNamed:@"chatBar_keyboard"] forState:UIControlStateNormal];
            self.faceBtn.tag = ButtonTypeKBButton;
            self.textView.hidden = NO;
            self.recoderBtn.hidden = YES;
            [self.speakBtn setImage:[UIImage imageNamed:@"chatBar_record"] forState:UIControlStateNormal];
            self.speakBtn.tag = ButtonTypeVoiceButton;
            [self.funcBtn setImage:[UIImage imageNamed:@"chatBar_more"] forState:UIControlStateNormal];
            self.funcBtn.tag = ButtonTypeFuncButton;

            [self.textView changeKeyBoardWithKeyBoardType:KeyBoardTypeWithFaceKeyBoard];
            
        }
            break;
        case ButtonTypeFuncButton:
        {
            [self.funcBtn setImage:[UIImage imageNamed:@"chatBar_keyboard"] forState:UIControlStateNormal];
            self.funcBtn.tag = ButtonTypeKBButton;
            self.textView.hidden = NO;
            self.recoderBtn.hidden = YES;
            [self.faceBtn setImage:[UIImage imageNamed:@"chatBar_face"] forState:UIControlStateNormal];
            self.faceBtn.tag = ButtonTypeFaceButton;
            [self.speakBtn setImage:[UIImage imageNamed:@"chatBar_record"] forState:UIControlStateNormal];
            self.speakBtn.tag = ButtonTypeVoiceButton;
            
            [self.textView changeKeyBoardWithKeyBoardType:KeyBoardTypeWithFunctionKeyBoard];
        }
            break;

        case ButtonTypeKBButton:
        {
            [self.speakBtn setImage:[UIImage imageNamed:@"chatBar_record"] forState:UIControlStateNormal];
            self.speakBtn.tag = ButtonTypeVoiceButton;
            self.textView.hidden = NO;
            self.recoderBtn.hidden = YES;
            [self.faceBtn setImage:[UIImage imageNamed:@"chatBar_face"] forState:UIControlStateNormal];
            self.faceBtn.tag = ButtonTypeFaceButton;
            [self.funcBtn setImage:[UIImage imageNamed:@"chatBar_more"] forState:UIControlStateNormal];
            self.funcBtn.tag = ButtonTypeFuncButton;
            
            [self.textView changeKeyBoardWithKeyBoardType:KeyBoardTypeWithSystemKeyBoard];
        }
            break;

        case ButtonTypeVoiceButton:
        {
            [self.speakBtn setImage:[UIImage imageNamed:@"chatBar_keyboard"] forState:UIControlStateNormal];
            self.speakBtn.tag = ButtonTypeKBButton;
            self.textView.hidden = YES;
            self.recoderBtn.hidden = NO;
            [self.faceBtn setImage:[UIImage imageNamed:@"chatBar_face"] forState:UIControlStateNormal];
            self.faceBtn.tag = ButtonTypeFaceButton;
            [self.funcBtn setImage:[UIImage imageNamed:@"chatBar_more"] forState:UIControlStateNormal];
            self.funcBtn.tag = ButtonTypeFuncButton;
            [self.textView resignFirstResponder];
        }
            break;
            
        default:
            break;
    }
}
-(void)stratRecord{
    
    [self.recoderBtn setTitle:@"松开结束" forState:UIControlStateNormal];
    // ios 7之后一定要实现
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [audioSession setActive:YES error:nil];
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"myRecorder.wav"];
    self.voice_url = [NSURL fileURLWithPath:path];

    // 1.创建录音器
    NSMutableDictionary *setting = [NSMutableDictionary dictionary];
    // 音频格式
    setting[AVFormatIDKey] = @(kAudioFormatLinearPCM);
    // 音频采样率
    setting[AVSampleRateKey] = @(8000.0);
    // 音频通道数
    setting[AVNumberOfChannelsKey] = @(1);
    // 线性音频的位深度
    setting[AVLinearPCMBitDepthKey] = @(16);
    self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:self.voice_url settings:setting error:nil];
    //缓冲
    // [self.audioRecorder prepareToRecord];
    //开始录音
    NSLog(@"开始录音");
    [self.audioRecorder record];
}

-(void)stopRecord{
    
    [self.recoderBtn setTitle:@"按住录音" forState:UIControlStateNormal];
    [self.audioRecorder stop];
    
    NSString * str =[self.voice_url.path substringToIndex:self.voice_url.path.length-3];
    NSString * amrPath=[NSString stringWithFormat:@"%@amr",str];
    BOOL zhuanhuan =[self convertWAV:self.voice_url.path toAMR:amrPath];
    if (zhuanhuan) {
        
        if (self.sendVoiceBlockHandle)
        {
            self.sendVoiceBlockHandle(self.voice_url);
        }
        
    }
}
-(void)cancelRecord{
    
    [self.audioRecorder stop];
    self.audioRecorder = nil;
    
}

- (BOOL)convertAMR:(NSString *)amrFilePath
             toWAV:(NSString *)wavFilePath
{
    BOOL ret = NO;
    BOOL isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:amrFilePath];
    if (isFileExists) {
        [EMVoiceConverter amrToWav:amrFilePath wavSavePath:wavFilePath];
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:wavFilePath];
        if (isFileExists) {
            ret = YES;
        }
    }
    
    return ret;
}

- (BOOL)convertWAV:(NSString *)wavFilePath
             toAMR:(NSString *)amrFilePath {
    BOOL ret = NO;
    BOOL isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:wavFilePath];
    if (isFileExists) {
        [EMVoiceConverter wavToAmr:wavFilePath amrSavePath:amrFilePath];
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:amrFilePath];
        if (!isFileExists) {
            
        } else {
            ret = YES;
        }
    }
    
    return ret;
}

@end
